'use strict';
angular.module('app.controllers')
  .controller('AdministratorMangeController', ['$scope', '$state', '$window', 'ngDialog', 'UserService', function($scope, $state, $window, ngDialog, UserService) {
    var vm = this;
    vm.currentPage = 1;
    vm.totalPages = 1;
    vm.pages = [];
    vm.getAllAdminUsers = function() {
      vm.pages = [];
      UserService.getAllAdminUsers(vm.currentPage).then(function(ret) {
        vm.users = ret.data.content;
        ret.data.totalElements == 0 ? vm.noRecord = true : vm.noRecord = false;
        vm.firstPage = ret.data.firstPage;
        vm.lastPage = ret.data.lastPage;
        vm.totalPages = ret.data.totalPages;
        var start = Math.max(0, vm.currentPage - 6);
        var end = Math.min(vm.currentPage + 6, vm.totalPages);
        for (var i = start; i < end; i++) {
          vm.pages.push(i + 1);
        }
      });
    };

    vm.getAllAdminUsers();

    vm.loadPage = function(page) {
      if (page > 0) {
        vm.currentPage = page;
        vm.getAllAdminUsers();
      }
    };

    vm.deleteUser = function (id) {
      if(confirm('确定要删除吗？')){
        UserService.deleteAdminUser(id).then(function () {
        alert('删除管理员用户成功！');
        vm.getAllAdminUsers();
      });
      }
      
    };

    vm.editAdminUser = function (user) {
      ngDialog.open({
        template: 'views/system/edit_admin_user.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width',
        controller: ['$scope', 'ngDialog', function ($scope, ngDialog) {
          $scope.memberId = user.memberId;
          $scope.email = user.email;
          $scope.mobile = user.mobile;

          $.extend($scope, {
            closeDialog: function() {
              ngDialog.closeAll();
            },

            saveUser: function () {
              UserService.saveAdmin({
                id: user.id,
                email: $scope.email,
                mobile: $scope.mobile
              }).then(function (ret) {
                if (ret.data.code) {
                  alert(ret.data.value);
                  return false;
                };
                alert("修改用户信息成功！");
                $scope.closeDialog();
                vm.getAllAdminUsers();
              });
            }
          });
        }],
        scope: $scope
      });
    };

    vm.createAdminUser = function () {
      ngDialog.open({
        template: 'views/system/create_admin_user.html',
        ariaAuto: false,
        className: 'ngdialog-theme-plain custom-width',
        controller: ['$scope', 'ngDialog', function ($scope, ngDialog) {
          var postData = {};
          var emailRegex = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
          
          var mobileRegex = /^(13[0-9]{9})|(14[0-9])|(18[0-9])|(15[0-9][0-9]{8})$/;

          $.extend($scope, {
            closeDialog: function() {
              ngDialog.closeAll();
            },

            checkFieldLength: function (field, start, end) {
              return !(!field || field.length < start || field.length > end);
            },

            showFieldTooltip: function (selector) {
              $(selector).popover('show');
            },

            closeFiledTooltip: function (selector) {
              $(selector).popover('destroy');
            },

            closeAllTooltip: function () {
              $scope.closeFiledTooltip('#password');
              $scope.closeFiledTooltip('#re-password');
              $scope.closeFiledTooltip('#email');
              $scope.closeFiledTooltip('#mobile');
            },

            checkPassword: function () {
              var user = $scope.user;
              var password = user.password ? $.trim(user.password) : '';

              postData['password'] = password;
              return $scope.checkFieldLength(password, 6, 12);
            },

            checkRePassword: function () {
              var user = $scope.user;
              var re_password = user.re_password;

              return re_password === postData['password'];
            },

            checkEmail: function () {
              var user = $scope.user;
              var email = user.email ? $.trim(user.email) : '';

              postData['email'] = email;
              return emailRegex.test(email);
            },

            checkMobile: function () {
              var user = $scope.user;
              var mobile = user.mobile ? $.trim(user.mobile) : '';

              postData['mobile'] = mobile;
              return mobileRegex.test(mobile);
            },

            checkUserInfo: function () {

              if (!$scope.checkPassword()) {
                $scope.showFieldTooltip('#password');
                return false;
              }

              if (!$scope.checkRePassword()) {
                $scope.showFieldTooltip('#re-password');
                return false;
              }

              if (!$scope.checkEmail()) {
                $scope.showFieldTooltip('#email');
                return false;
              }

              if (!$scope.checkMobile()) {
                $scope.showFieldTooltip('#mobile');
                return false;
              }
              postData['role'] = $scope.user.role;
              return true;
            },

            createUser: function () {
              if (!$scope.checkUserInfo()) {
                return false;
              }
              
              UserService.createNewAdmin({
                'userName': postData['username'],
                'password': hex_md5(postData['password']),
                'email': postData['email'],
                'mobile': postData['mobile'],
                'role': postData['role']
              }).then(function (ret) {
                if (ret.data.code) {
                  alert(ret.data.value);
                  return false;
                };
                alert('创建管理员用户成功!');
                $scope.closeDialog();
                vm.getAllAdminUsers();
              });
            }
          });
      }],
        scope: $scope
      });
    }
  }]);